package com.example.littleken.asynctasktext;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    public static final String APK_DOWNLOAD_URL = "http://download.sj.qq.com/upload/connAssitantDownload/upload/MobileAssistant_1.apk";
    private static final String TAG = "MainActivity";
    private ProgressBar mprogressBar;
    private TextView mTextView;
    private Button mButton;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        setListener();
        setData();

        DownloadHelper.download(APK_DOWNLOAD_URL, "", new DownloadHelper.onDownloadListener.onDownloadAdapter() {
            @Override
            public void onSuccess(int code, File file) {

            }

            @Override
            public void onFail(int code, File file, String message) {

            }
        });
    }

    private void setData() {
        mprogressBar.setProgress(0);
        mButton.setText("点击下载");
        mTextView.setText("准备下载");
    }

    private void setListener() {
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2018/4/23  下载任务
                downloadAsyncTask asyncTask = new downloadAsyncTask();
                //Task实例化必须在主线程中执行
                asyncTask.execute(APK_DOWNLOAD_URL);
                //execute()必须在主线程中执行
            }
        });
    }

    private void initView() {
        mprogressBar = (ProgressBar) findViewById(R.id.progressBar);
        mTextView = (TextView) findViewById(R.id.textView);
        mButton = (Button) findViewById(R.id.button);
    }

    /**
     * String 入参
     * Integer 进度
     * Boolean 返回值
     */
    public class downloadAsyncTask extends AsyncTask<String,Integer,Boolean> {
        String mFilePath;
        /**
         * 在异步任务前，在主线程中（开始前）
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //可操作UI
            mTextView.setText("下载中");
            mButton.setText("下载中");
            mprogressBar.setProgress(0);
        }

        /**
         * 后台跑的线程（进行中……）
         * @param params
         * @return
         */
        @Override
        protected Boolean doInBackground(String... params) {
            if(params != null && params.length > 0){//防御式编程
                String apkUrl = params[0];
                try {
                    URL url = new URL(apkUrl);
                    URLConnection urlConnection = url.openConnection();
                    InputStream inputStream = urlConnection.getInputStream();
                    //获得了下载内容的总长度
                    int contentLength = urlConnection.getContentLength();
                    //建立本地安放地址
                    //Environment.getExternalStorageDirectory()获取手机存储路径,返回String类型
                    mFilePath = Environment.getExternalStorageDirectory() + File.separator + "littleken.apk";
                    //对安放地址进行处理
                    File apkFile = new File(mFilePath);
                    if(apkFile.exists()){
                        boolean result = apkFile.delete();
                        if(!result){
                            return false;
                        }
                    }

                    int downloadSize = 0;//当前下载长度
                    byte[] bytes = new byte[1024];
                    int length;
                    //输出管道
                    OutputStream outputStream = new FileOutputStream(mFilePath);
                    while((length = inputStream.read(bytes)) > -1){
                        outputStream.write(bytes,0,length);
                        downloadSize += length;//获得当下下载进度
                        publishProgress(downloadSize * 100/contentLength);//让主线程更新进度条
                    }
                    inputStream.close();
                    outputStream.close();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    return false;
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }else {
                return false;
            }
            return true;
        }

        /**
         * 在主线程中，执行结果处理（事后）
         * @param aBoolean
         */
        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            mButton.setText(aBoolean? "下载完成":"下载失败");
            mTextView.setText(aBoolean? "下载完成" + mFilePath : "下载失败");
        }

        /**
         *在UI线程处理子线程进度
         * @param values
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //在  publishProgress();抛出的进度在这里会收到
            if(values != null && values.length > 0)
            mprogressBar.setProgress(values[0]);
        }

        /**
         * 这东西没啥用
         * @param aBoolean
         */
        @Override
        protected void onCancelled(Boolean aBoolean) {
            super.onCancelled(aBoolean);
        }

        /**
         *
         */
        @Override
        protected void onCancelled() {
            super.onCancelled();
        }
    }
}
